<template>
  <div>
    <!-- <el-button @click="importExcel">导入excel</el-button> -->
    <label for="file" class="el-button">导入excel</label>
    <input id="file" type="file" name="file" style="display: none" @change="importExcel">
    <el-button @click="exportExcel">导出Excel</el-button>
    <el-button @click="printPDF">保存PDF</el-button>
    <!-- <div class="table-box el-table" v-html="html" /> -->
    <el-table
      :data="tableData"
      style="width: 100%"
    >

      <el-table-column
        v-for="(item, index) in header"
        :key="item"
        :prop="fileds[index]"
        :label="item"
        width="180"
      />
    </el-table>
  </div>
</template>

<script>
import XLSX from 'xlsx'
export default {

  data() {
    return {
      html: '',
      tableData: [],
      header: ['一', '二', '三', '四', '五', '六', '七', '八'],
      fileds: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']
    }
  },
  methods: {
    // 导入excel
    importExcel(e) {
      console.log('导入excel:', e, e.target.files[0])

      var files = e.target.files; var f = files[0]
      var reader = new FileReader()
      reader.onload = (e) => {
        var data = new Uint8Array(e.target.result)
        var workbook = XLSX.read(data, { type: 'array' })
        console.log('workbook:', workbook)
        var first_worksheet = workbook.Sheets[workbook.SheetNames[0]]
        // var data1 = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 })
        console.log('json:', XLSX.utils.sheet_to_json(first_worksheet, { header: 1 }))
        console.log('json:', XLSX.utils.sheet_to_html(first_worksheet, { header: 1 }))
        console.log('json:', XLSX.utils.sheet_to_csv(first_worksheet, { header: 1 }))
        // this.html = XLSX.utils.sheet_to_html(first_worksheet, { header: 1 })

        const jsonData = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 })

        this.tableData = this.formatExcelData(jsonData)

        /* DO SOMETHING WITH workbook HERE */
      }
      reader.readAsArrayBuffer(f)
    },
    // 导出excel
    exportExcel() {
      var workbook = XLSX.utils.table_to_book(document.querySelector('table'))
      console.log(workbook)
      XLSX.writeFile(workbook, 'test.xlsx')
    },
    formatExcelData(jsonArr) {
      return jsonArr.map(v => {
        const obj = {}
        v.forEach((v1, i) => {
          obj[this.fileds[i]] = v1
        })
        return obj
      })
    },
    printPDF() {
      window.print()
    }
  }
}
</script>

<style>
  .table-box table {
    width: 80%;
    border-collapse: collapse;
  }

  .table-box td {
    border: 1px solid #eee;
    text-align: center;
  }
</style>
